//index.js
//获取应用实例
const app = getApp()

import { Base } from '../../../utils/base.js';
var base = new Base();//初始化对象


var userInfo;
var page = 1; //当前页面
var last_page = 1; //最后一页页面
var dataList = [];
Page({
  data: {
    TabCur: 0,
    scrollLeft:0,
    hasUserInfo:false,
    row:{}
  },
  //tarbar切换
  onTabItemTap(item) {
    console.log(item.pagePath)
    console.log(item.text)
    this.updateLoginStatus();
  },

  onLoad: function () {
    
    var that = this;
    //监听用户登录信息
    app.event.on('userInfo', this, function (ret) {
      //更新登录状态
      that.updateLoginStatus();
    })

    that.updateLoginStatus();

  },

  //上拉加载更多页面
  onReachBottom:function(){

    page = page + 1;
    //获取订单信息
    this.getOrderList();

  },

  //刷新登录状态
  updateLoginStatus:function(){
    userInfo = wx.getStorageSync('userInfo');
    if( userInfo ){
      this.setData({
        hasUserInfo: true
      })

      //获取订单信息
      this.getOrderList();
    } else {
      this.setData({
        hasUserInfo: false
      })
    }
  },

  tabSelect(e) {
    this.setData({
      TabCur: e.currentTarget.dataset.id,
      scrollLeft: (e.currentTarget.dataset.id-1)*60
    })

    page = 1;
    last_page = 1;
    //获取订单信息
    this.getOrderList();
  },

  //获取订单信息
  getOrderList:function(){
    var that = this;

    userInfo = wx.getStorageSync('userInfo');
    if( !userInfo ){
        //未登录
      
      return false;
    }

    if( page > last_page ){
      base._toast( '暂无更多订单' );
      return true;
    }
    base._ajax(base.Conf.serverUrl + "v1/order/list", {
      token: userInfo.token, 
      type:this.data.TabCur,
      page:page
    }, 'post', function (ret) {
      if( ret.errcode == 0){
        last_page = ret.data.last_page;

        if( ret.data.total > 0){
          dataList[page - 1] = ret.data.data;
          that.setData({
            row: dataList,
            total:ret.data.total
          })
        } else {
          that.setData({
            row: {},
            total:0
          })
        }
        

      }

    });

  },

  //取消订单
  cancelOrder:function( e ){
    var that = this;
    base._ajax(base.Conf.serverUrl + "v1/order/cancel", {
      token: userInfo.token, 
      order_id:e.currentTarget.dataset.id
    }, 'post', function (ret) {
      if( ret.errcode == 0){
        //刷新页面，
        base._toast( '订单已取消' );

        //获取订单信息
        page = 1;
        last_page = 1;
        that.getOrderList();

      } else {
        base._toast(ret.errmsg );
      }
      

    });

  },


  //订单详情
  orderDetail:function(e){

    var id = e.currentTarget.dataset.id;
    base._link_page("/pages/order/detail/index?order_id=" + id ,1);

  },

  //支付
  pay:function(e){

  }

  
})
